/*
 * @Author: XPectuer
 * @LastEditor: XPectuer
 */
package main

import (
	"fmt"
	"os"
	"strings"
	"sync"

	"github.com/eatmoreapple/openwechat"
	"github.com/sirupsen/logrus"
)

func init() {
	logrus.SetFormatter(&logrus.TextFormatter{TimestampFormat: "2006-01-02 15:04:05"})
	logrus.SetOutput(os.Stdout)
	logrus.SetLevel(logrus.InfoLevel)
}

func names(user *openwechat.User) string {
	return " Name In Group | RemarkName: " + user.RemarkName + "\nNickName: " + user.NickName + "\nAlias: " + user.Alias + "\nUserName: " + user.UserName + "\nDisplayName:" + user.DisplayName
}


func isVolunteer(fullstr string) bool {
	return strings.Contains(fullstr, "五四") || strings.Contains(fullstr, "54")
}
func getSenderName(sender *openwechat.User) string {
	displayname := sender.DisplayName
	if displayname != "" {
		return displayname
	} else {
		return sender.NickName
	}
}


func g(msg *openwechat.Message) {
	/*
		Alias             string
		DisplayName       string
	*/

	sender, err := msg.SenderInGroup()
	if err != nil {
		logrus.WithError(err).Error("Failed to get sender in group")
	} else {
		uuid := sender.UserName
		senderName := getSenderName(sender)
		isVol := isVolunteer(senderName)
		wordCount :=  CountWords(msg.Content)
		
		if isVol {
			logrus.Infof("Sender info: %s", names(sender))
			logrus.Infof("Message content: %s", msg.Content)
			
			// singleton
			db:= InitDB()
			 
			user := NewUserFromDB(db, uuid, senderName)
			user.AddWordCount(wordCount)
			logrus.Infof("User info: %s", user.String())
			
			// todo: write back to DB
			res, err := UpdateWordCount(db, user)
			if err != nil {
				logrus.Errorf("UpdateWordCount error: %s", err)
			} else {
				logrus.Infof("UpdateWordCount success")
			}

			logrus.Infof("Update Word Count For %s With Res: %s", uuid, res)
			
		} else {
			logrus.Debugf("Sender info: %s", names(sender))
			logrus.Debugf("Message content: %s", msg.Content)
		}
	}
}

func WriteMsgAsUser(msg *openwechat.Message) {
	// todo: judge specified chatRoom
	if msg.IsText() && msg.IsSendByGroup() {
		go g(msg)
	}

}

func initBot() (*openwechat.Bot, error) {
	bot := openwechat.DefaultBot(openwechat.Desktop) // 桌面模式

	// 注册消息处理函数
	bot.MessageHandler = WriteMsgAsUser
	// 注册登陆二维码回调
	bot.UUIDCallback = openwechat.PrintlnQrcodeUrl
	
	// 登陆
	if err := bot.Login(); err != nil {
		fmt.Println(err)
		return nil, err
	}

	// 获取登陆的用户
	_, err := bot.GetCurrentUser()
	if err != nil {
		fmt.Println(err)
		return nil, err
	}

	//  // 获取所有的好友
	//  friends, err := self.Friends()
	//  fmt.Println(friends, err)

	//// 获取所有的群组
	// groups, err := self.Groups()
	// fmt.Println(groups, err)

	// res := groups.SearchByNickName(1, "机器小狗测试")

	// for _, member := range res.AsMembers() {
	// 	println(names(member))
	// }

	// 阻塞主goroutine, 直到发生异常或者用户主动退出
	return bot, nil
}

func main() {
	bot, err := initBot()
	if err != nil {
		logrus.Fatal(err)
	}

	var wg sync.WaitGroup
	wg.Add(1)

	bot.Block()
}
